package com.relytosoft.mizar.analyze.common.filter;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.relytosoft.dubhe.common.core.object.ResponseResult;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.mizar.analyze.common.config.properties.MizarAnalyzeProperties;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 基本权限验证
 *
 * @author Jierry
 * @version 2022/5/10.
 */
public class AuthFilter implements Filter {

    @Resource
    private MizarAnalyzeProperties mizarAnalyzeProperties;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String path = URLUtil.getPath(request.getRequestURL().toString());
        if ("/favicon.ico".equals(path) || ArrayUtil.contains(mizarAnalyzeProperties.getExcludes(), path)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        try {
            String keyName = "key";
            if (StrUtil.isNotEmpty(request.getParameter(keyName)) && StrUtil.isNotEmpty(mizarAnalyzeProperties.getKey())) {
                Object key = RedisUtil.get(keyName);
                if (ObjectUtil.isEmpty(key)) {
                    key = mizarAnalyzeProperties.getKey();
                    RedisUtil.set(keyName, key, 36000L);
                }
                if (request.getParameter(keyName).equals(key)) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
            servletResponse.setContentType("application/json; charset=utf-8");
            final PrintWriter writer = servletResponse.getWriter();
            writer.write(JSON.toJSONString(ResponseResult.fail("获取Key失败")));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            servletResponse.setContentType("application/json; charset=utf-8");
            final PrintWriter writer = servletResponse.getWriter();
            writer.write(JSON.toJSONString(ResponseResult.fail(e.getMessage())));
            writer.flush();
            writer.close();
        }
    }
}
